package com.dingwei.superiordiary.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bobomee.android.mentions.edit.MentionEditText;
import com.bobomee.android.mentions.edit.util.FormatRangeManager;
import com.bobomee.android.mentions.text.MentionTextView;
import com.bumptech.glide.Glide;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.adapter.CommentDetailsEvaluationListAdapter;
import com.dingwei.superiordiary.app.MyApplication;
import com.dingwei.superiordiary.bean.MoreReplyBean;
import com.dingwei.superiordiary.bean.MyCarePersonalBean;
import com.dingwei.superiordiary.mvp.presenter.MoreReplyPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.parser.Parser;
import com.dingwei.superiordiary.utils.ShareDialogUtils;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.KeyboardUtils;
import com.lihao.baselibrary.weight.MyGridView;
import com.lihao.baselibrary.weight.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/1/30.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class MoreReplyActivity extends BaseActivity implements Contract.CommentMoreReplyView {

    MoreReplyPresenter moreReplyPresenter = new MoreReplyPresenter(this);
    @Bind(R.id.main_titleBar)
    TitleBar mainTitleBar;
    @Bind(R.id.img_head)
    ImageView imgHead;
    @Bind(R.id.tv_nick_name)
    TextView tvNickName;
    @Bind(R.id.tv_level)
    TextView tvLevel;
    @Bind(R.id.tv_signature)
    TextView tvSignature;
    @Bind(R.id.tv_add_time)
    TextView tvAddTime;
    @Bind(R.id.tv_content)
    MentionTextView tvContent;
    @Bind(R.id.gridview)
    MyGridView gridview;
    @Bind(R.id.tv_evaluation_num)
    TextView tvEvaluationNum;
    @Bind(R.id.img_like)
    ImageView imgLike;
    @Bind(R.id.tv_like_num)
    TextView tvLikeNum;
    @Bind(R.id.like_layout)
    LinearLayout likeLayout;
    @Bind(R.id.ic_tread)
    ImageView icTread;
    @Bind(R.id.tv_tread_num)
    TextView tvTreadNum;
    @Bind(R.id.tread_layout)
    LinearLayout treadLayout;
    @Bind(R.id.tv_sort)
    TextView tvSort;
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.et_comment)
    MentionEditText etComment;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;
    @Bind(R.id.data_layout)
    LinearLayout dataLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    @Bind(R.id.tv_attention)
    TextView tvAttention;
    private FormatRangeManager mRangeManager;
    private Parser mTagParser = new Parser();
    private String id;

    private int page = 1;
    private int type = 2;


    CommentDetailsEvaluationListAdapter mAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.acticity_comment_details;
    }

    @Override
    protected void initData() {
        moreReplyPresenter.initData(id, page, type, true, true);
    }

    @Override
    protected void initView() {

        mRangeManager = new FormatRangeManager();
        tvContent.setMovementMethod(new LinkMovementMethod());
        tvContent.setParserConverter(mTagParser);

        id = getIntent().getStringExtra("id");
        mAdapter = new CommentDetailsEvaluationListAdapter(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setAdapter(mAdapter);
        refreshLayout.setEnableLoadmoreWhenContentNotFull(true);

    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                moreReplyPresenter.initData(id, page, type, false, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                moreReplyPresenter.initData(id, page, type, true, false);
            }
        });

        mainTitleBar.setOnMenuListener(new TitleBar.OnMenuListener() {
            @Override
            public void onMenuClick() {
                moreReplyPresenter.showMeunPopupWindow(mainTitleBar.getMenu(), bean.data.is_collect);
            }
        });

        mAdapter.setReplyInterface(new CommentDetailsEvaluationListAdapter.ReplyInterface() {
            @Override
            public void likes(int position) {
                MoreReplyBean.DataBean.SubBean bean = mAdapter.getItem(position);
                moreReplyPresenter.commentLike(bean.id, position);
            }

            @Override
            public void cai(int position) {
                MoreReplyBean.DataBean.SubBean bean = mAdapter.getItem(position);
                moreReplyPresenter.commentCai(bean.id, position);
            }

            @Override
            public void subUser(String user_id) {
                intent = new Intent(BaseActivity.context, LookUserCenterActivity.class);
                intent.putExtra("user_id", user_id);
                startActivity(intent);
            }

            @Override
            public void more(int position) {
            }
        });

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1 && !TextUtils.isEmpty(s)) {
                    char mentionChar = s.toString().charAt(start);
                    int selectionStart = etComment.getSelectionStart();
                    if (mentionChar == '@') {
                        intent = new Intent(BaseActivity.context, aitePersonalActivity.class);
                        intent.putExtra("userid", BaseActivity.value.getUserId());
                        startActivityForResult(intent, 1001);
                        etComment.getText().delete(selectionStart - 1, selectionStart);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public void replySuccess(String content) {
        refreshLayout.autoRefresh();
        etComment.setText("");
    }

    MoreReplyBean bean;

    @Override
    public void OnRefresh(boolean isRefresh, MoreReplyBean bean) {
        this.bean = bean;
        Glide.with(BaseActivity.context)
                .load(bean.data.portrait)
                .apply(MyApplication.headOptions)
                .into(imgHead);
        tvNickName.setText(bean.data.nickname);
        tvLevel.setText("LV." + bean.data.level);
        tvSignature.setText(bean.data.idiograph);
        tvAddTime.setText(bean.data.addtime);
        String s = bean.data.content.replaceAll("'>", "'>@");
        tvContent.setText(s);


        if (bean.data.is_liked == 1) {
            imgLike.setImageResource(R.mipmap.ic_liked);
        } else {
            imgLike.setImageResource(R.mipmap.ic_like);
        }
        tvLikeNum.setText(bean.data.likes + "");
        tvTreadNum.setText(bean.data.trample + "");
        tvEvaluationNum.setText(bean.data.comment_total + "");
        if (BaseActivity.value.getUserId().equals(bean.data.consumer_id)) {
            tvAttention.setVisibility(View.GONE);
        } else {
            tvAttention.setVisibility(View.VISIBLE);
            if (bean.data.attentioned==0) {
                tvAttention.setText("+关注");
                tvAttention.setTextColor(ContextCompat.getColor(BaseActivity.context, R.color.theme_color));
                tvAttention.setBackgroundResource(R.drawable.theme_line_bg);
            } else {
                tvAttention.setText("已关注");
                tvAttention.setTextColor(ContextCompat.getColor(BaseActivity.context, R.color.white));
                tvAttention.setBackgroundResource(R.drawable.theme_bg);
            }
        }

        mAdapter.clear();
        mAdapter.addAll(bean.data.sub);
        refreshLayout.finishRefresh();

        showData("success");
    }

    private void showData(String state) {
        if (state.equals("success")) {
            dataLayout.setVisibility(View.VISIBLE);
            noNetLayout.setVisibility(View.GONE);
        } else {
            dataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void OnLoadMore(boolean isRefresh, MoreReplyBean bean) {
        mAdapter.addAll(bean.data.sub);
        refreshLayout.finishLoadmore();
        showData("success");
    }

    @Override
    public void onFail() {
        showData("fail");
    }

    @Override
    public void Report() {
        intent = new Intent(context, ReportActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);
    }

    @Override
    public void likeSuccess() {
    }

    @Override
    public void shield() {
        moreReplyPresenter.shieldComment(id);
    }

    @Override
    public void shieldCommentSuccess() {
        finish();
    }

    @Override
    public void SetHotSort() {
        tvSort.setText("热门");
        page = 1;
        type = 3;
        moreReplyPresenter.initData(id, page, type, true, true);
    }

    @Override
    public void SetZhengSort() {
        tvSort.setText("正序");
        page = 1;
        type = 2;
        moreReplyPresenter.initData(id, page, type, true, true);
    }

    @Override
    public void collect() {
        moreReplyPresenter.activityCollect(bean.data.activity_id, bean.data.is_collect);
    }

    @Override
    public void share() {
        ShareDialogUtils.showShareDialog(this, bean.data.share_data.url, bean.data.share_data.title, bean.data.share_data.img, bean.data.share_data.desc, "11", shareListener);
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(MoreReplyActivity.this, "分享成功", Toast.LENGTH_LONG).show();
            SocializeUtils.safeCloseDialog(dialog);
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(MoreReplyActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(MoreReplyActivity.this, "取消分享", Toast.LENGTH_LONG).show();

        }
    };

    @Override
    public void report() {
        intent = new Intent(BaseActivity.context, ReportActivity.class);
        intent.putExtra("id", bean.data.id);
        startActivity(intent);
    }


    @Override
    public void collectSuccess() {
        if (bean.data.is_collect == 1) {
            bean.data.is_collect = 0;
        } else {
            bean.data.is_collect = 1;
        }
    }

    @Override
    public void commentLikeSuccess(int position) {
        if (position == -1) {
            if (bean.data.is_liked == 1) {
                bean.data.is_liked = 1;
                bean.data.likes = bean.data.likes - 1;
                imgLike.setImageResource(R.mipmap.ic_like);
            } else {
                bean.data.is_liked = 0;
                bean.data.likes = bean.data.likes + 1;
                imgLike.setImageResource(R.mipmap.ic_liked);
            }
            tvLikeNum.setText(bean.data.likes + "");
        } else {
            MoreReplyBean.DataBean.SubBean bean = mAdapter.getItem(position);
            if (bean.is_liked == 1) {
                bean.is_liked = 0;
                bean.likes = (Integer.parseInt(bean.likes) - 1) + "";
            } else {
                bean.is_liked = 1;
                bean.likes = (Integer.parseInt(bean.likes) + 1) + "";
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void trampleCommentSuccess(int position) {
        if (position == -1) {
        } else {
            MoreReplyBean.DataBean.SubBean bean = mAdapter.getItem(position);
            if (bean.is_trample==0){
                bean.is_trample = 1;
                bean.trample = (Integer.parseInt(bean.trample) + 1) + "";
                showToast("踩成功");
            }else {
                showToast("取消成功");
                bean.is_trample = 0;
                bean.trample = (Integer.parseInt(bean.trample) - 1) + "";
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void attentionActionSuccess() {
        bean.data.attentioned = bean.data.attentioned == 0 ? 1 : 0;
        if (bean.data.attentioned==0) {
            tvAttention.setText("+关注");
            tvAttention.setTextColor(ContextCompat.getColor(BaseActivity.context, R.color.theme_color));
            tvAttention.setBackgroundResource(R.drawable.theme_line_bg);
        } else {
            tvAttention.setText("已关注");
            tvAttention.setTextColor(ContextCompat.getColor(BaseActivity.context, R.color.white));
            tvAttention.setBackgroundResource(R.drawable.theme_bg);
        }
    }

    @Override
    public void SetDaoSort() {
        tvSort.setText("倒序");
        page = 1;
        type = 1;
        moreReplyPresenter.initData(id, page, type, true, true);
    }

    @OnClick({R.id.img_head, R.id.tv_attention, R.id.like_layout, R.id.tread_layout, R.id.btn_submit, R.id.no_net_btn, R.id.tv_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_head:
                intent = new Intent(BaseActivity.context, LookUserCenterActivity.class);
                intent.putExtra("user_id", bean.data.consumer_id);
                startActivity(intent);
                break;
            case R.id.tv_attention:
                if (bean.data.attentioned == 0) {
                    moreReplyPresenter.attentionAction(bean.data.consumer_id, "1");
                } else {
                    moreReplyPresenter.attentionAction(bean.data.consumer_id, "0");
                }
                break;
            case R.id.like_layout:
                moreReplyPresenter.commentLike(bean.data.id, -1);
                break;
            case R.id.tread_layout:
                moreReplyPresenter.commentCai(bean.data.id, -1);
                break;
            case R.id.tv_sort:
                moreReplyPresenter.showSortPopupWindow(tvSort);
                break;
            case R.id.btn_submit:
                CharSequence convertMetionString = etComment.getFormatCharSequence();
                moreReplyPresenter.saveComment(bean.data.activity_id, bean.data.id, convertMetionString.toString());
                KeyboardUtils.hideSoftInput(this);
                break;
            case R.id.no_net_btn:
                page = 1;
                moreReplyPresenter.initData(id, page, type, true, true);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001) {
            MyCarePersonalBean.DataBean.ListBean user = (MyCarePersonalBean.DataBean.ListBean) data.getSerializableExtra("user");
            etComment.insert(user);
        }
    }
}
